<!-- components/TagsView.vue -->
<template>
  <div class="tags-view-wrapper dis-jb">
    <!-- 标签容器：横向滚动 -->
    <div class="tags-view-scroll">
      <el-tag
        v-for="tag in visitedViews"
        :key="tag.path"
        :closable="!affix(tag)"
        :effect="isActive(tag) ? 'dark' : 'plain'"
        class="tags-view-item"
        @click="router.push(tag.path)"
        @close="delView(tag)"
        @contextmenu.prevent="openMenu($event, tag)"
      >
        {{ tag.title }}
      </el-tag>
    </div>

    <!-- 右键菜单 -->
    <el-dropdown
      @command="handleCommand"
      @visible-change="(visible) => !visible && closeMenu()"
    >
      <el-icon size="20" color="#666" class="el-icon--right">
        <Discount />
      </el-icon>
      <template #dropdown>
        <el-dropdown-menu>
          <el-dropdown-item command="closeOther" :disabled="single"
            >关闭其他</el-dropdown-item
          >
          <el-dropdown-item command="closeAll">关闭全部</el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>
  </div>
</template>

<script lang="ts" setup>
import { ref } from "vue";
import { useTagsViewStore } from "@/store/tags";
import { storeToRefs } from "pinia";
import { useRouter } from "vue-router";
import type { TagView } from "@/store/tags";

const tagsViewStore = useTagsViewStore();
const router = useRouter();
const { visitedViews } = storeToRefs(tagsViewStore);

const { delView, isActive, delOthersViews, delAllViews } = tagsViewStore;

// 当前右键的标签
const contextMenuTag = ref<TagView | null>(null);
const menuVisible = ref(false);
const menuLeft = ref(0);
const menuTop = ref(0);

const affix = (tag: TagView) => {
  return tag.path === "/dashboard"; // 固定标签（不能关闭）
};

const single = computed(() => {
  return visitedViews.value.length <= 1;
});

// 打开右键菜单
const openMenu = (e: MouseEvent, tag: TagView) => {
  contextMenuTag.value = tag;
  menuVisible.value = true;
};

// 关闭菜单
const closeMenu = () => {
  menuVisible.value = false;
  contextMenuTag.value = null;
};

// 菜单命令
const handleCommand = (command: string) => {
  if (!contextMenuTag.value) return;
  switch (command) {
    case "closeOther":
      delOthersViews(contextMenuTag.value);
      break;
    case "closeAll":
      delAllViews();
      break;
  }
  closeMenu();
};
</script>

<style scoped>
.tags-view-wrapper {
  height: 40px;
  background-color: #f5f5f5;
  border-bottom: 1px solid #ddd;
  position: relative;
}

.tags-view-scroll {
  display: flex;
  align-items: center;
  white-space: nowrap;
  overflow-x: auto;
  overflow-y: hidden;
  padding: 0 10px;
  height: 100%;
  scrollbar-width: thin;
}

.tags-view-scroll::-webkit-scrollbar {
  height: 6px;
}

.tags-view-scroll::-webkit-scrollbar-thumb {
  background-color: #ccc;
  border-radius: 3px;
}

.tags-view-item {
  margin-right: 6px;
  border: none;
  /* color: #fff; */
  cursor: pointer;
  font-size: 13px;
  height: 30px;
  display: flex;
  align-items: center;
  padding: 0 12px;
}
</style>
